<?php
namespace Admin\Model;

class DatadictModel extends AbstractModel {

	protected $results = array();
	public $_validate = array(
        array('Name','require','请输入类型名称')
    );
	
	public function Myadd(){
		if(!$this->create()){
			$this->results['msg'] = $this->getError();
			$this->results['state'] = 0;
		}else{
			if($this->Myshow(array("Name" => I('POST.Name')))){
				$this->results['state'] = 0;
				$this->results['msg'] = "类型名称已存在！";	
			}else{
				$res = $this->add();
				if($res){
					$this->results['state'] = 1;
					$this->results['msg'] = "添加成功！";
					$this->results['id'] = $res;
				}else{
					$this->results['state'] = 0;
					$this->results['msg'] = "添加失败！";	
				}
			}
		}
		return $this->results;
	}
	
	public function Myupdata(){
		if(!$this->create()){
			$this->results['msg'] = $this->getError();
			$this->results['state'] = 0;
		}else{
			$res = $this->save();
			if($res) {
				$this->results['state'] = 1;
				$this->results['msg'] = "修改成功！";
				$this->results['id'] = $res;
			}else{
				$this->results['state'] = 0;
				$this->results['msg'] = "修改错误！";
			}
		}
		return $this->results;
	}
	
	public function Myshow($parmArr){
		$where = " 1 ";
		foreach($parmArr AS $key => $value){
			$where .= " AND $key = '$value'"; 
		}
		$sql = " SELECT * FROM datadict WHERE $where AND IsDel = 0";
		$res = $this->query($sql);
		return $res;
	}
	
	public function MyshowList($type){
		$where = " 1 ";
		$wherein = "";
		$keyword = I('keyword');
		if(!empty($keyword)){
			$sql = "SELECT ID FROM datadict WHERE Name like '%$keyword%' AND IsDel = 0";
			$res = $this->query($sql);
			foreach($res AS $k => $v){
				$wherein .= $v['ID'].',';
			}
			$wherein = substr($wherein,0,-1);
			$where .= " AND ParentID != 0 AND Name like '%$keyword%' OR ParentID in ($wherein)";
		}else {
			if($type == 1){
				$where .= " AND ParentID != 0 ";
			}else{
				$where .= " AND ParentID = 0 ";
			}
		}
		$return = array();
		/*
		if($type == 1){
			$sql = " SELECT COUNT(*) count FROM datadict WHERE $where AND IsDel = 0";
		}else{
			$sql = " SELECT COUNT(*) count FROM datadict WHERE $where AND IsDel = 0";
		}
		*/
		$sql = " SELECT COUNT(*) count FROM datadict WHERE $where AND IsDel = 0";
		$count = $this->query($sql);
		$count = $count[0]['count'];
	    $page = $this->Mypage($count, 20);

		if($type == 1){
			$sql = " SELECT *,(SELECT Name FROM datadict WHERE ID = a.ParentID) AS Pname FROM datadict AS a WHERE $where AND IsDel = 0 ORDER BY ID DESC LIMIT $page->firstRow , $page->listRows";
		}else{
			$sql = " SELECT * FROM datadict WHERE $where AND IsDel = 0 ORDER BY ID DESC LIMIT $page->firstRow , $page->listRows";
		}
		$res = $this->query($sql);
		$return['list'] = $res;
		$return['page'] = $page->show('Admin');
		return $return;
	}
	
}

?>				